package com.nature.ffmpegforandroid

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.SurfaceHolder
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.content.ContextCompat

/**
 *User: RandBII
 *Date: 2020/12/31
 *Description:
 *
 */
class NativeMediaPlayActivity : AppCompatActivity(), SurfaceHolder.Callback,
    NatureMediaPlayer.EventCallback {

    var surfaceView: MySurfaceView? = null
    var natureMediaPlayer: NatureMediaPlayer? = null
    var seekerBar: AppCompatSeekBar? = null
    var mIsTouch = false
    var mVideoPath = ""

    companion object {
        val NEED_PERMISSIONS =
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.MODIFY_AUDIO_SETTINGS
            )
        const val REQUEST_PERMISSION_CODE = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_native_mediaplay)
        mVideoPath = "${Environment.getExternalStorageDirectory().absolutePath}/zmg.mp4"


        surfaceView = findViewById(R.id.surface_view)
        seekerBar = findViewById(R.id.seek_bar)
        surfaceView?.holder?.addCallback(this)

        seekerBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                mIsTouch = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                natureMediaPlayer?.let {
                    it.seekToPosition(seekBar?.progress?.toFloat() ?: 0f)
                    mIsTouch = false
                }
            }
        })


    }


    override fun surfaceCreated(holder: SurfaceHolder) {
        natureMediaPlayer = NatureMediaPlayer()
        natureMediaPlayer?.mEventCallback = this
        if (TextUtils.isEmpty(mVideoPath)) {
            Log.e("NativeMediaPlay-->", "$mVideoPath")
        }
        natureMediaPlayer?.natureMediaPlayerInit(
            mVideoPath,
            NatureMediaPlayer.VIDEO_RENDER_ANWINDOW,
            holder.surface
        )
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        natureMediaPlayer?.play()
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        natureMediaPlayer?.unInit()
    }

    override fun onPlayerEvent(msgType: Int, msgValue: Float) {
        runOnUiThread {
            when (msgType) {
                NatureMediaPlayer.MSG_DECODING_TIME -> {

                }
                NatureMediaPlayer.MSG_DECODER_READY -> {

                    Log.e(
                        "onPlayerEvent ",
                        "nativeMediaPlayActivity NatureMediaPlayer.MSG_DECODER_READY "
                    )
                    onDecoderReady()
                }
                else -> Log.e("onPlayerEvent ", "this is else ")
            }

        }
    }

    private fun onDecoderReady() {
        val videoWidth =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_WIDTH) ?: 0
        val videoHeight =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_HEIGHT) ?: 0

        if (videoHeight * videoWidth != 0L) surfaceView?.setAspectRatio(
            videoWidth.toInt(),
            videoHeight.toInt()
        )
        val duration =
            natureMediaPlayer?.getMediaParams(NatureMediaPlayer.MEDIA_PARAM_VIDEO_DURATION)?.toInt()
                ?: 0
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) seekerBar?.min = 0
        seekerBar?.max = duration

    }

    override fun onResume() {
        super.onResume()

        if (!hasPermissions(NEED_PERMISSIONS)) {
            requestPermissions(
                NEED_PERMISSIONS,
                REQUEST_PERMISSION_CODE
            )
        } else {
            natureMediaPlayer?.play()
        }


    }

    override fun onPause() {
        super.onPause()
        natureMediaPlayer?.pause()
    }

    private fun hasPermissions(permissions: Array<String>): Boolean {
        var has = true
        for (permission in permissions) {
            has = has and (ContextCompat.checkSelfPermission(
                this,
                permission
            ) == PackageManager.PERMISSION_GRANTED)
        }
        return has
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (!hasPermissions(permissions as Array<String>)) {
                Toast.makeText(this, "请授予相应的权限", Toast.LENGTH_SHORT).show()
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults)
            }
        }
    }


}